package com.xu.t1.middleware.Thread;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 用于管理维护应用中的线程
 *
 * @author xu
 *
 */

@Service
public class ThreadCounterService {

    private static final String THREAD_COUNT_KEY = "app:thread_count";

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 线程维护 参数为正数加 负数减
    public int updateThreadCount(int delta) {

        if (delta != 1 && delta != -1) {
            throw new IllegalArgumentException("线程计数增量只能为 +1 或 -1");
        }

        Long newCount = redisTemplate.opsForValue().increment(THREAD_COUNT_KEY, delta);

        return newCount != null ? newCount.intValue() : 0;
    }

    // 获取当前线程数
    public int getThreadCount() {
        String countStr = redisTemplate.opsForValue().get(THREAD_COUNT_KEY);
        if (countStr == null) {
            return 0;
        }
        try {
            return Integer.parseInt(countStr);
        } catch (NumberFormatException e) {
            //  首次未开启任何线程时 可重置为0
            resetThreadCount();
            return 0;
        }
    }

    // 重置线程数
    public void resetThreadCount() {
        redisTemplate.opsForValue().set(THREAD_COUNT_KEY, "0");
    }
}